/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vista;

import controladores.CargoJpaController;
import controladores.EmpleadoJpaController;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.InputMap;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.table.DefaultTableModel;
import modelo.Cargo;
import modelo.Empleado;

/**
 *
 * @author Ususario
 */
public class GestionEmpleado extends javax.swing.JInternalFrame {

    List<String> empleados = new ArrayList<String>();
    private DefaultTableModel modelo1;
    String datos1[][] = {};
    String columnas1[] = {"Codigo", "Tipo", "Cedula", "Nombre", "Salario", "Cargo"};
    boolean nuevo = false;
    EmpleadoJpaController eC = new EmpleadoJpaController();
    CargoJpaController cC = new CargoJpaController();
    DecimalFormat df = new DecimalFormat();
    
    public GestionEmpleado() {
        modelo1 = new DefaultTableModel(datos1, columnas1);
        df.setMaximumFractionDigits(2);
        initComponents();
        List<Empleado> empleados = eC.findEmpleadoEntities();
        for (int i = 0; i < empleados.size(); i++) {
            Empleado b = empleados.get(i);
            modelo1.addRow(new Object[]{});
            modelo1.setValueAt(b.getIdempleado(), i, 0);
            modelo1.setValueAt(b.getTipo(), i, 1);
            modelo1.setValueAt(b.getCedula(), i, 2);
            modelo1.setValueAt(b.getNombre(), i, 3);

            modelo1.setValueAt(df.format(b.getSalario()), i, 4);
            modelo1.setValueAt(b.getCargoIdcargo().getNombre(), i, 5);
        }
        masterTable.setModel(modelo1);
        InputMap im = masterTable.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        im.put(KeyStroke.getKeyStroke("DOWN"), "none");
        im.put(KeyStroke.getKeyStroke("UP"), "none");

        cargoField.removeAllItems();
        List<Cargo> cargos = cC.findCargoEntities();
        for (Cargo cargo : cargos) {
            cargoField.addItem(cargo.getCodigo() + "-" + cargo.getNombre());
        }



    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable(){
            public boolean isCellEditable(int rowIndex, int colIndex) {
                return false;   //Disallow the editing of any cell

            }};
            idempleadoLabel = new javax.swing.JLabel();
            tipoLabel = new javax.swing.JLabel();
            cedulaLabel = new javax.swing.JLabel();
            nombreLabel = new javax.swing.JLabel();
            salarioLabel = new javax.swing.JLabel();
            cargoIdcargoLabel = new javax.swing.JLabel();
            idempleadoField = new javax.swing.JTextField();
            cedulaField = new javax.swing.JTextField();
            nombreField = new javax.swing.JTextField();
            salarioField = new javax.swing.JTextField();
            saveButton = new javax.swing.JButton();
            refreshButton = new javax.swing.JButton();
            newButton = new javax.swing.JButton();
            deleteButton = new javax.swing.JButton();
            cargoField = new javax.swing.JComboBox();
            tipoField = new javax.swing.JComboBox();

            setTitle("Gestionar empleados");
            setPreferredSize(new java.awt.Dimension(885, 440));

            jPanel1.setPreferredSize(new java.awt.Dimension(800, 370));

            masterTable.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {

                },
                new String [] {
                    "Codigo", "Tipo", "Cedula", "Nombre", "Salario", "Cargo"
                }
            ));
            masterTable.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    masterTableMouseClicked(evt);
                }
            });
            masterScrollPane.setViewportView(masterTable);

            idempleadoLabel.setText("Codigo:");

            tipoLabel.setText("Tipo:");

            cedulaLabel.setText("Cedula:");

            nombreLabel.setText("Nombre:");

            salarioLabel.setText("Salario:");

            cargoIdcargoLabel.setText("Cargo:");

            idempleadoField.setEnabled(false);

            cedulaField.setEnabled(false);

            nombreField.setEnabled(false);

            salarioField.setEnabled(false);

            saveButton.setText("Guardar");
            saveButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    saveButtonActionPerformed(evt);
                }
            });

            refreshButton.setText("Refrescar");
            refreshButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    refreshButtonActionPerformed(evt);
                }
            });

            newButton.setText("Nuevo");
            newButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    newButtonActionPerformed(evt);
                }
            });

            deleteButton.setText("Borrar");
            deleteButton.setEnabled(false);
            deleteButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    deleteButtonActionPerformed(evt);
                }
            });

            cargoField.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
            cargoField.setEnabled(false);

            tipoField.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Contratista", "Planta" }));
            tipoField.setEnabled(false);

            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                            .addComponent(newButton)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(deleteButton)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(refreshButton)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(saveButton))
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addContainerGap()
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(idempleadoLabel)
                                        .addComponent(tipoLabel)
                                        .addComponent(cedulaLabel)
                                        .addComponent(nombreLabel)
                                        .addComponent(salarioLabel)
                                        .addComponent(cargoIdcargoLabel))
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(idempleadoField, javax.swing.GroupLayout.DEFAULT_SIZE, 735, Short.MAX_VALUE)
                                        .addComponent(cedulaField, javax.swing.GroupLayout.DEFAULT_SIZE, 735, Short.MAX_VALUE)
                                        .addComponent(nombreField, javax.swing.GroupLayout.DEFAULT_SIZE, 735, Short.MAX_VALUE)
                                        .addComponent(salarioField, javax.swing.GroupLayout.DEFAULT_SIZE, 735, Short.MAX_VALUE)
                                        .addComponent(cargoField, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(tipoField, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                                .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE))))
                    .addContainerGap())
            );
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(idempleadoLabel)
                        .addComponent(idempleadoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(tipoLabel)
                        .addComponent(tipoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(cedulaLabel)
                        .addComponent(cedulaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(nombreLabel)
                        .addComponent(nombreField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(salarioLabel)
                        .addComponent(salarioField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(cargoIdcargoLabel)
                        .addComponent(cargoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(saveButton)
                        .addComponent(refreshButton)
                        .addComponent(deleteButton)
                        .addComponent(newButton))
                    .addContainerGap())
            );

            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 869, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 35, Short.MAX_VALUE)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 34, Short.MAX_VALUE)))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 411, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 20, Short.MAX_VALUE)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 21, Short.MAX_VALUE)))
            );

            pack();
        }// </editor-fold>//GEN-END:initComponents

    public static boolean isNumeric(String cadena) {
        try {
            Float.parseFloat(cadena);
            return true;
        } catch (NumberFormatException nfe) {
            return false;
        }
    }

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        try {
            if (idempleadoField.getText().trim().equals("") || nombreField.getText().trim().equals("")
                    || cedulaField.getText().trim().equals("") || salarioField.getText().trim().equals("") || !this.isNumeric(salarioField.getText().trim().replaceAll("\\.", ""))) {
                JOptionPane.showMessageDialog(null, "Por favor llene todos los campos");
            } else {
                if (nuevo && eC.findEmpleado(idempleadoField.getText().trim().toUpperCase()) != null) {
                    JOptionPane.showMessageDialog(null, "Ya existe un empleado registrado con este codigo", "Error", JOptionPane.ERROR_MESSAGE);
                } else {
                    if (!nuevo) {
                        Empleado seleccionado = eC.findEmpleado(idempleadoField.getText());
                        seleccionado.setNombre(nombreField.getText().trim().toUpperCase());
                        seleccionado.setCedula(cedulaField.getText().trim().toUpperCase());
                        seleccionado.setSalario(Float.parseFloat(salarioField.getText().trim().replaceAll("\\.", "")));
                        seleccionado.setTipo(tipoField.getSelectedItem().toString());
                        String partes[] = cargoField.getSelectedItem().toString().split("-");
                        String codC = partes[0];
                        Cargo car = cC.findBySingle("codigo", codC);
                        seleccionado.setCargoIdcargo(car);
                        eC.edit(seleccionado);
                        List<Empleado> empleados = eC.findEmpleadoEntities();
                        modelo1 = new DefaultTableModel(datos1, columnas1);
                        for (int i = 0; i < empleados.size(); i++) {
                            Empleado aux = empleados.get(i);
                            modelo1.addRow(new Object[]{});
                            modelo1.setValueAt(aux.getIdempleado(), i, 0);
                            modelo1.setValueAt(aux.getTipo(), i, 1);
                            modelo1.setValueAt(aux.getCedula(), i, 2);
                            modelo1.setValueAt(aux.getNombre(), i, 3);
                            modelo1.setValueAt(aux.getSalario(), i, 4);
                            modelo1.setValueAt(aux.getCargoIdcargo().getNombre(), i, 5);
                        }
                        masterTable.setModel(modelo1);
                        idempleadoField.setEnabled(false);
                        idempleadoField.setText("");
                        tipoField.setEnabled(false);
                        cedulaField.setEnabled(false);
                        cedulaField.setText("");
                        nombreField.setEnabled(false);
                        nombreField.setText("");
                        salarioField.setEnabled(false);
                        salarioField.setText("");
                        cargoField.setEnabled(false);
                        nuevo = false;


                    } else {
                        Empleado nuevoE = new Empleado();
                        nuevoE.setIdempleado(idempleadoField.getText().trim().toUpperCase());
                        nuevoE.setTipo(tipoField.getSelectedItem().toString());
                        nuevoE.setCedula(cedulaField.getText().trim().toUpperCase());
                        nuevoE.setNombre(nombreField.getText().trim().toUpperCase());
                        nuevoE.setSalario(Float.parseFloat(salarioField.getText().trim().replaceAll("\\.", "")));
                        nuevoE.setTipo(tipoField.getSelectedItem().toString());
                        String partes[] = cargoField.getSelectedItem().toString().split("-");
                        String codC = partes[0];
                        Cargo car = cC.findBySingle("codigo", codC);
                        nuevoE.setCargoIdcargo(car);
                        eC.create(nuevoE);
                        modelo1.addRow(new Object[]{});
                        modelo1.setValueAt(nuevoE.getIdempleado(), masterTable.getRowCount() - 1, 0);
                        modelo1.setValueAt(nuevoE.getTipo(), masterTable.getRowCount() - 1, 1);
                        modelo1.setValueAt(nuevoE.getCedula(), masterTable.getRowCount() - 1, 2);
                        modelo1.setValueAt(nuevoE.getNombre(), masterTable.getRowCount() - 1, 3);
                        modelo1.setValueAt(nuevoE.getSalario(), masterTable.getRowCount() - 1, 4);
                        modelo1.setValueAt(nuevoE.getCargoIdcargo().getNombre(), masterTable.getRowCount() - 1, 5);
                        masterTable.setModel(modelo1);
                        idempleadoField.setEnabled(false);
                        idempleadoField.setText("");
                        tipoField.setEnabled(false);
                        cedulaField.setEnabled(false);
                        cedulaField.setText("");
                        nombreField.setEnabled(false);
                        nombreField.setText("");
                        salarioField.setEnabled(false);
                        salarioField.setText("");
                        cargoField.setEnabled(false);
                        nuevo = false;
                    }
                }



            }

        } catch (Exception rex) {
            /*rex.printStackTrace();
             entityManager.getTransaction().begin();
             List<vista.Banco> merged = new ArrayList<vista.Banco>(list.size());
             for (vista.Banco b : list) {
             merged.add(entityManager.merge(b));
             }
             list.clear();
             list.addAll(merged);*/
        }
    }//GEN-LAST:event_saveButtonActionPerformed

    private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
        masterTable.clearSelection();
        idempleadoField.setEnabled(false);
        idempleadoField.setText("");
        tipoField.setEnabled(false);
        cedulaField.setEnabled(false);
        cedulaField.setText("");
        nombreField.setEnabled(false);
        nombreField.setText("");
        salarioField.setEnabled(false);
        salarioField.setText("");
        cargoField.setEnabled(false);
        nuevo = false;
    }//GEN-LAST:event_refreshButtonActionPerformed

    private void newButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newButtonActionPerformed
        masterTable.clearSelection();
        idempleadoField.setEnabled(true);
        idempleadoField.setText("");
        tipoField.setEnabled(true);
        cedulaField.setEnabled(true);
        cedulaField.setText("");
        nombreField.setEnabled(true);
        nombreField.setText("");
        salarioField.setEnabled(true);
        salarioField.setText("");
        cargoField.setEnabled(true);
        nuevo = true;
    }//GEN-LAST:event_newButtonActionPerformed

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
    }//GEN-LAST:event_deleteButtonActionPerformed

    private void masterTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_masterTableMouseClicked
        Empleado p = eC.findEmpleado((String) modelo1.getValueAt(masterTable.getSelectedRow(), 0));
        idempleadoField.setText(p.getIdempleado());
        tipoField.setEnabled(true);
        if (p.getTipo().equals("Planta")) {
            tipoField.setSelectedIndex(1);
        } else {
            tipoField.setSelectedIndex(0);
        }
        cedulaField.setEnabled(true);
        cedulaField.setText(p.getCedula());
        nombreField.setEnabled(true);
        nombreField.setText(p.getNombre());
        salarioField.setEnabled(true);
        salarioField.setText(df.format(p.getSalario()));
        int cargos = cargoField.getItemCount();
        cargoField.setEnabled(true);
        for (int i = 0; i < cargos; i++) {
            String partes[] = cargoField.getItemAt(i).toString().split("-");
            if (partes[0].equals(p.getCargoIdcargo().getCodigo())) {
                cargoField.setSelectedIndex(i);
                break;
            }

        }

        nuevo = false;

    }//GEN-LAST:event_masterTableMouseClicked
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cargoField;
    private javax.swing.JLabel cargoIdcargoLabel;
    private javax.swing.JTextField cedulaField;
    private javax.swing.JLabel cedulaLabel;
    private javax.swing.JButton deleteButton;
    private javax.swing.JTextField idempleadoField;
    private javax.swing.JLabel idempleadoLabel;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.swing.JButton newButton;
    private javax.swing.JTextField nombreField;
    private javax.swing.JLabel nombreLabel;
    private javax.swing.JButton refreshButton;
    private javax.swing.JTextField salarioField;
    private javax.swing.JLabel salarioLabel;
    private javax.swing.JButton saveButton;
    private javax.swing.JComboBox tipoField;
    private javax.swing.JLabel tipoLabel;
    // End of variables declaration//GEN-END:variables
}
